package com.example.jasonrpc.example;

import com.example.jasonrpc.client.ClientConfig;
import com.example.jasonrpc.client.RpcClient;
import com.example.jasonrpc.client.byRegistry.RpcClientByRegistry;
import com.example.jasonrpc.client.byRegistry.RpcClientConfigByRegistry;
import com.example.jasonrpc.client.simple.RpcClientConfig;
import com.example.jasonrpc.client.simple.SimpleRpcClient;
import com.example.jasonrpc.registry.RegistryCenter;
import com.example.jasonrpc.registry.RegistryDirectory;
import com.example.jasonrpc.registry.redis.RedisRegistry;

import java.rmi.RemoteException;
import java.util.List;

/**
 * todo: 服务端ip改为放在配置文件
 */
public class Client {
    public static void main(String[] args) throws RemoteException {
        String serverIp = ConfigUtil.getServerIp("config");
        int serverPort = ConfigUtil.getServerPort("config");
        int centerPort = ConfigUtil.getCenterPort("config");
        //增加注册中心后，启动时先订阅注册中心读取主机，服务方法信息，再传给rpc客户端调用
        startClientByRegistry(serverIp, centerPort);
        //不使用注册中心
//        String serviceClass = "com.example.jasonrpc.example.CalcService";
//        RpcClient client = new SimpleRpcClient(new RpcClientConfig(serverIp, serverPort));
//
//        CalcService proxy = client.getProxy(serviceClass);
//        System.out.println(proxy.add(12, 3));
//        System.out.println(proxy.add(2, 3));
//        System.out.println(proxy.add(12, 3));
//        System.out.println(proxy.substract(2, 3));
    }


    private static void startClientByRegistry(String centerIp, int centerPort) throws RemoteException {
        RegistryCenter center = new RedisRegistry(centerIp, centerPort);
        String serviceClass = "com.example.jasonrpc.example.CalcService";
        List<RegistryDirectory> subscribe = center.subscribe(serviceClass);
        String serviceClass2 = "com.example.jasonrpc.example.StringService";
        List<RegistryDirectory> subscribe2 = center.subscribe(serviceClass2);
        subscribe.addAll(subscribe2);

        ClientConfig configByRegistry = new RpcClientConfigByRegistry(subscribe);
        RpcClient client = new RpcClientByRegistry(configByRegistry);

        CalcService proxy = client.getProxy(serviceClass);
        System.out.println(proxy.add(2, 3));
        System.out.println(proxy.substract(2, 3));
        StringService s = client.getProxy(serviceClass2);
        System.out.println(s.greeting("Hello"));
    }
}
